<template>
<div class="full-height page-content stop-set">
    <p class="sub-title padding-l-20 padding-r-20"><span class="gray-txt"> 当{{statusList[1].label}}时长符合以下设置，系统会自动识别{{statusList[1].label}}原因</span></p>
    <q-scroll-area ref="scrollArea" style="height: 100%; max-width: 100%" :thumbStyle="CommonConfig.thumbStyle">
       <!--停机设置-->
       <div style="padding: 20px 20px 0">
         <div class="flex justify-between items-center">
           <p class="sub-title">小停机 <span class="gray-txt">({{statusList[1].label}}时长 ≤ xS)</span></p>
           <q-btn style="width: 96px; min-height: 32px; font-size: 16px"
                  class="btn" label="保存" color="primary" @click="saveStopSet(1)" />
         </div>
         <slider v-model="smallStop" :max="300" :min="0" />
      </div>
      <div style="padding: 20px 20px 0">
        <div class="flex justify-between items-center">
          <p class="sub-title margin-t-30">取放停机 <span class="gray-txt">({{statusList[1].label}}时长为循环取放时长的 x% ~ y%)</span></p>
          <q-btn style="width: 96px; min-height: 32px; font-size: 16px; padding: 0 16px"
                 class="qa-btn" label="保存" color="primary" @click="saveStopSet(2)" />
        </div>
        <q-range v-model="stopRange" :min="0" :max="500" label label-color="dark" class="margin-t-20"/>
      </div>
<!--      自定义停机-->
      <div style="padding: 20px 20px 0">
        <div class="flex justify-between items-center q-mb-lg">
          <p class="sub-title margin-t-30">自定义 <span class="gray-txt">（最多创建5条自定义数据，每条数据的{{statusList[1].label}}时长不能重叠，{{statusList[1].label}}原因不能重复）</span></p>
        </div>
        <q-table
          :data="tableData"
          :columns="columns"
          row-key="id"
          class="myTable scroll stick-last-col"
          :loading="isTableLoading"
          :pagination.sync="pagination"
          style="margin: 0;"
          hide-bottom
          color="primary"
        >
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td key="index" :props="props">
                {{ tableData.indexOf(props.row) + 1 }}
              </q-td>
              <q-td key="stopTimeMin" :props="props">
                <template v-if="props.row.edit">
                  <div class="flex padding-t-10">
                    <yz-input style="width: 120px"
                              input-type="select"
                              v-model="props.row.stopTimeMin"
                              :options="stopTimeOptions"
                              title=""></yz-input>
                    <div class="q-ml-sm q-mt-sm">～</div>
                    <yz-input style="width: 120px"
                              input-type="select"
                              v-model="props.row.stopTimeMax"
                              :options="stopTimeOptions"
                              title=""></yz-input>
                  </div>
                </template>
                <span v-else>{{ setStopTime(props.row) }}</span>
              </q-td>
              <q-td key="stopTypeId" :props="props">
                <template v-if="props.row.edit">
                  <yz-input style="width: 260px"
                            input-type="select"
                            class="padding-t-10"
                            v-model="props.row.stopTypeId"
                            @input="onSelectStopType(props.row)"
                            :options="stopTypeList"
                            :title="`${statusList[1].label}类型`" :rules="[0]"></yz-input>
                </template>
                <span v-else>{{ props.row.causeGroupDesc }}</span>
              </q-td>
              <q-td key="stopCauseId" :props="props">
                <template v-if="props.row.edit">
                  <yz-input style="width: 260px"
                            input-type="select"
                            class="padding-t-10"
                            v-model="props.row.stopCauseId"
                            :options="stopCauseList"
                            :title="`${statusList[1].label}原因`" :rules="[0]"></yz-input>
                </template>
                <span v-else>{{ props.row.causeDesc }}</span>
              </q-td>
              <q-td class="operations" style="width: 100px">
                <div class="btn-group text-center" v-if="props.row.edit">
                  <table-btn btnType="submit" @click="onSubmit(props.row)"/>
                  <table-btn btnType="cancel" @click="onCancel(props.row)"/>
                </div>
                <div class="btn-group text-center" v-else>
                  <table-btn btnType="edit" @click="onEdit(props.row)" :disable="isEdit"/>
                  <table-btn btnType="delete" @click="onDelete(props.row)" :disable="isEdit"/>
                </div>
              </q-td>
            </q-tr>
          </template>
        </q-table>
          <q-btn flat
                 v-if="tableData.length < 5"
                 dense
                 color="primary"
                 style="height: 48px"
                 @click="onAdd"
                 :disable="isEdit"
                 class="full-width">
            <q-icon name="iconfont icontubiao-39"
                    class="q-mr-sm" />
            添加
          </q-btn>
      </div>
    </q-scroll-area>
</div>
</template>
<script>
import Slider from 'src/components/slider'
import { mapGetters } from 'vuex'
import { getCauseTypeList, getSelectTenantList, putStopCustom, postStopCustom, delStopCustom } from 'src/boot/system/reason-new'
import _ from 'lodash'
import { getCauseItemNew } from 'src/boot/system/reason'
export default {
  name: 'stop-set',
  components: {
    Slider
  },
  data () {
    return {
      smallStop: 5, // 小停机值
      stopRange: { min: 50, max: 200 }, // 取放时长,
      stopData: [],
      stopDialog: 0,
      tableData: [],
      cloneTableData: [],
      stopTypeList: [],
      stopCauseList: [],
      isEdit: false,
      isTableLoading: false,
      pagination: {
        rowsPerPage: 0
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'statusList']),
    columns () {
      return [
        { name: 'index', label: '序号', align: 'left', field: 'index' },
        { name: 'stopTimeMin', label: `${this.statusList[1].label}时长（分钟）`, align: 'left', field: 'stopTimeMin' },
        { name: 'stopTypeId', label: `${this.statusList[1].label}类型`, align: 'left', field: 'stopTypeId' },
        { name: 'stopCauseId', label: `${this.statusList[1].label}原因`, align: 'left', field: 'stopCauseId' },
        { name: 'operations', label: '操作', align: 'center', field: 'operations' }
      ]
    },
    stopTimeOptions () {
      return _.range(0, 1000).map(v => {
        return {
          label: v,
          value: Number(v * 60)
        }
      })
    }
  },
  methods: {
    hitRule (row) {
      const newTableData = row.id ? this.cloneTableData.filter(v => v.id !== row.id) : this.cloneTableData
      const member = newTableData.reduce((arr, item) => {
        const v = _.range(item.stopTimeMin / 60, Number(item.stopTimeMax) / 60)
        arr.push(...v)
        return arr
      }, [])
      const isUniq = _.difference(member, _.range(row.stopTimeMin / 60, Number(row.stopTimeMax) / 60))
      const stopCauseIdList = newTableData.map(v => v.stopCauseId)
      if (row.stopCauseId === '' || row.stopTypeId === '') {
        this.$message.warning(`${this.statusList[1].label}类型或${this.statusList[1].label}原因为空`)
        return false
      }
      if (!_.lt(Number(row.stopTimeMin), Number(row.stopTimeMax))) {
        this.$message.warning(`${this.statusList[1].label}开始时间要小于结束时间`)
        return false
      }
      if (isUniq.length !== member.length) {
        this.$message.warning(`自定义${this.statusList[1].label}的时间区间有重叠`)
        return false
      }
      if (stopCauseIdList.includes(row.stopCauseId)) {
        this.$message.warning(`自定义${this.statusList[1].label}原因有重复`)
        return false
      }
      return true
    },
    onSubmit (row) {
      if (!this.hitRule(row)) return
      const params = {
        ...row,
        tenantId: this.userInfo.tenant_id
      }
      _.isNil(row.id) ? postStopCustom(params).then(() => {
        this.getList()
        this.$message.success('保存成功！')
      }).catch(e => e) : this.putStopCustom(params)
    },
    onEdit (row) {
      this.isEdit = true
      this.stopCauseList = []
      this.getCauseItem(row.stopTypeId, () => {
        row.edit = true
        // 如果返回数组不存在当前停机原因则显示空
        if (_.findIndex(this.stopCauseList, { value: row.stopCauseId }) < 0) {
          row.stopCauseId = ''
        }
        this.$set(this.tableData, row.__index, row)
      })
    },
    onDelete (row) {
      this.$utils.showMessage('icontubiao-28', '确定要删除此项吗?', () => {
        delStopCustom(row.id).then(() => {
          this.getList()
          this.$message.success('删除成功！')
        }).catch(e => e)
      }, true)
    },
    onCancel () {
      this.isEdit = false
      this.getList()
      // this.tableData = _.initial(this.tableData)
    },
    onAdd () {
      // 点击添加行
      this.isEdit = true
      this.stopCauseList = []
      const data = {
        index: this.tableData.length + 1,
        stopCauseId: '',
        stopTypeId: '',
        priority: 100,
        stopTimeMin: 0,
        stopTimeMax: 0,
        edit: true
      }
      this.tableData.push(data)
    },
    setStopTime (row) {
      return `${Math.floor(row.stopTimeMin / 60)} - ${Math.floor(row.stopTimeMax / 60)}`
    },
    // 保存停机设置
    saveStopSet (priority) {
      //  priority 1 小停机， 2 取放停机， 100 自定义
      const member = _.find(this.stopData, { priority })
      console.log(member)
      const stopTimeMax = priority === 1 ? this.smallStop : this.stopRange.max
      const stopTimeMin = priority === 1 ? 0 : this.stopRange.min
      let params = {
        priority,
        id: member?.id,
        stopTimeMax,
        stopTimeMin,
        tenantId: this.userInfo.tenant_id,
        stopCauseId: member?.stopCauseId,
        stopTypeId: member?.stopTypeId
      }
      this.putStopCustom(params)
    },
    putStopCustom (params) {
      putStopCustom(params).then(() => {
        this.getList()
        this.$message.success('保存成功！')
      }).catch(e => e)
    },
    getList () {
      this.isEdit = false
      const tenantId = this.userInfo.tenant_id
      this.isTableLoading = true
      getSelectTenantList(tenantId).then(res => {
        this.isTableLoading = false
        const ret = res.data
        //  priority 1 小停机， 2 取放停机， 100 自定义
        this.stopData = ret
        this.smallStop = _.find(ret, { 'priority': 1 })?.stopTimeMax || 0
        const stopRange = _.find(ret, { 'priority': 2 })
        this.stopRange.max = stopRange.stopTimeMax || 0
        this.stopRange.min = stopRange.stopTimeMin || 0
        this.tableData = _.filter(ret, { 'priority': 100 }).map((v, index) => {
          const item = v
          item.indexId = index + 1
          item.edit = false
          return item
        })
        this.cloneTableData = _.cloneDeep(this.tableData)
      }).catch(e => e)
    },
    onSelectStopType (row) {
      row.stopCauseId = ''
      this.getCauseItem(row.stopTypeId)
    },
    // 获取原因类型列表
    getCauseTypeList (isDel = false) {
      getCauseTypeList(3, false).then(res => {
        this.stopTypeList = res.data.map(v => {
          return {
            ...v,
            value: v.id
          }
        }) || []
      })
    },
    // 根据停机原因类型代码查询停机原因
    getCauseItem (typeId, func) {
      this.stopCauseList = []
      const params = {
        id: typeId,
        showDisable: false
      }
      getCauseItemNew(params).then(res => {
        this.stopCauseList = res.data.map(v => {
          return {
            ...v,
            value: v.id
          }
        }) || []
        func && func()
      })
    }
  },
  mounted () {
    this.getList()
    this.getCauseTypeList()
  }
}
</script>
<style lang="stylus" scoped>
.stop-set{
  .sub-title{
    margin-bottom 0
    .gray-txt{
      color #999
    }
  }
}

</style>
